from django import http
from django.core.cache import cache
from django.shortcuts import render
from django.views import View


from apps.areas.models import Area
from utils.response_code import RETCODE


class AreaView(View):
    def get(self,request):
        area_id = request.GET.get('area_id')

        if area_id is not None:
            sub_list = cache.get('sub_area_%s'%area_id)
            if sub_list is None:

                areas = Area.objects.filter(parent_id=area_id)
                sub_list = []
                for area in areas:
                    sub_list.append({
                        'id':area.id,
                        'name':area.name
                    })
                cache.set('sub_area_%s'%area_id,sub_list,24*3600)
            return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK',"sub_list":sub_list})
        else:
            pro_list=cache.get('pro_list')
            if pro_list is None:
                # 3.如果没有area_id ,则省的数据
                areas = Area.objects.filter(parent=None)

                # 3.1.将对象列表转换为字典列表
                pro_list = []
                for area in areas:
                    pro_list.append({
                        'id': area.id,
                        'name': area.name
                    })
                cache.set('pro_list',pro_list,24*3600)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'provinces': pro_list})
